/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-05-12 20:52:37
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-05-12 23:12:53
 * @FilePath: /lesson40/1.sem_cp/maic.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <ctime>
#include "Ringqueue.hpp"
#include "Task.hpp"

using namespace std;

struct ThreadData
{
    Ringqueue<Task> *rq_;
    string tname;
};

void *Productor(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    Ringqueue<Task> *rq = td->rq_;
    string name = td->tname;
    int len = opers.size();

    while (1)
    {
        int data1 = rand() % 10 + 1;
        usleep(10);
        int data2 = rand() % 5;
        char op = opers[rand() % len];
        Task t(data1, data2, op);

        rq->Push(t);
        cout << "Productor task done: " << t.GetTask() << " ,name: " << name << endl;
        // sleep(1);
    }
    return nullptr;
}

void *Consumer(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    Ringqueue<Task> *rq = td->rq_;
    string name = td->tname;

    while (1)
    {
        Task t; // 记得补一个默认构造
        rq->Pop(&t);
        t();
        cout << "Consumer get task , result: " << t.Getret() << " ,name: " << name << endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    Ringqueue<Task> *rq = new Ringqueue<Task>();

    pthread_t c[1], p[1];
    for (int i = 0; i < 1; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq_ = rq;
        td->tname = "Consumer - " + to_string(i + 1);
        pthread_create(p + i, nullptr, Consumer, td);
    }
    for (int i = 0; i < 1; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq_ = rq;
        td->tname = "Productor - " + to_string(i + 1);
        pthread_create(c + i, nullptr, Productor, td);
    }

    for (int i = 0; i < 1; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 1; i++)
    {
        pthread_join(p[i], nullptr);
    }

    return 0;
}
